package com.csnf.demo1.servlet;

import com.csnf.demo1.entity.Student;
import com.csnf.demo1.service.StudentService;
import com.csnf.demo1.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;

@WebServlet(name = "StudentServlet", value = {"/StudentServlet","/getAllStudent","/getStudent"})
public class StudentServlet extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        String path = req.getServletPath();
        switch (path){
            case "/getAllStudent":
                getAllStudent(req,resp);
                break;
            case "/getStudent":
                getStuById(req,resp);
                break;
        }

    }
    private void  getStuById(HttpServletRequest req, HttpServletResponse resp){
        String queryid = req.getParameter("queryid");
        List<Student> stuList= null;
        try {
            stuList = studentService.getStudentById(Integer.valueOf(queryid));
//        Student stu=new Student();
            req.setAttribute("stuList",stuList);
            req.getRequestDispatcher("student.jsp").forward(req,resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private void getAllStudent(HttpServletRequest req, HttpServletResponse resp) {
        try {
            req.setAttribute("students",studentService.getAllStudent());
            req.getRequestDispatcher("student.jsp").forward(req, resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        //获取页面填写信息
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String sBirthday = req.getParameter("birthday");
        LocalDate birthday = LocalDate.parse(sBirthday);
        String clazz = req.getParameter("clazz");
        String state = req.getParameter("state");
        //通过信息创建学生对象
        Student student = new Student(null,name,gender,birthday,clazz,state);
        Boolean flag =false;
        try {
            flag = studentService.addStudent(student);  //调用保存方法
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            req.setAttribute("msg","失败");
        }else{
            req.setAttribute("msg","成功");
        }
        req.getRequestDispatcher("msg.jsp").forward(req,resp);
    }
}
